import 'package:flutter/material.dart';
import 'dart:async';
import 'package:hairen_app/pages/plug/func.dart';
import 'package:hairen_app/pages/player/player.dart';
import 'package:hairen_app/server/databases.dart';
import 'package:flutter/cupertino.dart';
import 'package:quiver/time.dart';
import 'package:hairen_app/pages/plug/drawer.dart';

class ViewHistory extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new _ViewHistoryState();
  }
}

class _ViewHistoryState extends State<ViewHistory> {
  ScrollController _scrollController = new ScrollController();
  bool downType = true;
  bool isLoading = false;
  bool stopLoading = false;

  int curPage = 0;
  List<Map> historyList = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getHistory();
//监听下拉加载更多
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        print(isLoading);
        if (!isLoading) {
          this.isLoading = true;
          getHistory();
        }
      }
    });
  }

  @override
  void dispose() {
    _scrollController.dispose();
    // TODO: implement dispose
    super.dispose();
  }

  getHistory() async {
    this.curPage += 1;
    if(!stopLoading){
      DataBases db = new DataBases();
      await db.open_table();
      db.query_view_table_list(curPage: curPage).then((rows) {
        List data = rows;
        if(data.length==0){
          stopLoading=true;
        }
        setState(() {
          for(var i=0;i<data.length;i++){
            historyList.add(data[i]);
          }
          this.isLoading = false;
        });
      });
    }
  }

  clearHistory() async {
    DataBases db = new DataBases();
    await db.open_table();
    db.del_table_list().then((state) {
      setState(() {
        stopLoading=false;
      });
      getHistory();
    });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
        drawer: new DrawerPage(),
        appBar: AppBar(
            elevation: 0.0,
            title: new Text("最近观看"),
            leading: new Builder(builder: (context) {
              return new IconButton(
                  icon: new Icon(Icons.menu),
                  onPressed: () {
                    Scaffold.of(context).openDrawer();
                  });
            }),
            actions: <Widget>[
              new Container(
                child: IconButton(
                    icon: new Icon(Icons.clear_all),
                    onPressed: () {
                      func.confirm(context, '是否清空浏览记录', (bool status) {
                        if (status) {
                          clearHistory();
                        }
                      });
                    }),
              ),
              new SizedBox(
                width: 10.0,
              )
            ]),
        body: new Container(
          padding: EdgeInsets.all(10.0),
          child: new ListView(
              controller: _scrollController,
              children: historyList.map((item) {
                DateTime time = DateTime.parse(item['time']);
                String title = item['title'].toString().substring(
                    0, item['title'].length > 20 ? 20 : item['title'].length);
                String sutitle = item['sutitle'].toString().substring(0,
                    item['sutitle'].length > 10 ? 10 : item['sutitle'].length);
                return new ListTile(
                    title: new Row(
                      children: <Widget>[
                        new Text("${title}..."),
                      ],
                    ),
                    subtitle: new Row(
                      children: <Widget>[
                        new Expanded(
                          flex: 3,
                          child: new Row(
                            children: <Widget>[
                              new Icon(
                                Icons.ondemand_video,
                                size: 14.0,
                              ),
                              new SizedBox(
                                width: 10.0,
                              ),
                              new Text(
                                "${sutitle}  (${item['ptime']})",
                              ),
                            ],
                          ),
                        ),
                        new Expanded(
                          flex: 1,
                          //${time.year}/${time.month}
                          child: new Text(
                            "${time.month}月${time.day} ${time.hour}:${time.minute}",
                            textAlign: TextAlign.right,
                          ),
                        )
                      ],
                    ),
                    trailing: new Icon(
                      Icons.chevron_right,
                      size: 35.0,
                    ),
                    onTap: () {
                      var timeArr = item['ptime'].toString().split(":");
                      var curtime = Duration(
                          hours: int.parse(timeArr[0]),
                          minutes: int.parse(timeArr[1]),
                          seconds: int.parse(timeArr[2]));
                      Navigator.of(context).push(new CupertinoPageRoute(
                          builder: (context) => new PlayerPage(
                                mid: item['mid'],
                                playTime: curtime,
                                setNumber: item['sutitle'],
                              )));
                    });
              }).toList()),
        ));
  }
}
